function Dnew = save_raw_tra_to_D(Draw,Dnew)
%SAVE_RAW_TRA_TO_D
% save the tra matrix before it is mucked aroud in AFRICA or the forward
% model. 
%
% D = SAVE_RAW_TRA_TO_D(DOLD) upgrades legacy formatting of tra matrix from
%   old AFRICA to new formatting
%
% D = SAVE_RAW_TRA_TO_D(DRAW, D) copies tra matrix from before
%    pre-processing, held in the DRAW SPM object, to D.
% 
% See also: osl_forward_model, osl_africa. 

% load files in
if nargin == 0;
    Draw = spm_eeg_load;
    Dnew = Draw;
elseif nargin == 1;
    Dnew = Draw;
end%if

if ischar(Dnew); Dnew = spm_eeg_load(Dnew); end
if ischar(Draw); Draw = spm_eeg_load(Draw); end

% extract sensor structure
grad = Draw.sensors('MEG');

% save the raw sensors field
if ~isfield(Dnew,'raw_sensors'),
    addedRawSensors  = true;
    Dnew.raw_sensors = grad;
else
    addedRawSensors = false;
    disp(['Dnew SPM object already has raw_sensors saved. ', ...
          'Using this matrix rather than overwriting.']);
end%if

% check for old syntax, from old pre-processing
if isfield(Dnew, 'raw_tra_matrix'),
    if isequal(Dnew.raw_tra_matrix, Dnew.raw_sensors.tra),
        warning([mfilename ':DeprecatedField'],               ...
                ['Deprecated field D.raw_tra_matrix found. ', ...
                 'This will be ignored. \n']);
        Dnew = rmfield(Dnew, 'raw_tra_matrix');
        
    elseif addedRawSensors
        % this indicates that we are running data with old preprocessing.
        % We should therefore use the raw_tra_matrix field. 
        warning([mfilename ':DeprecatedFieldUsed'],                       ...
                ['Deprecated field D.raw_tra_matrix found. \n',           ...
                 'It will be used to set D.raw_sensors.tra. \n',          ...
                 'This suggests that you are analysing data which were ', ...
                 'pre-processed in an older version of OSL. \n\n',        ...
                 'Check this assertion!\n']);
             
        Dnew.raw_sensors.tra = Dnew.raw_tra_matrix;
        Dnew                 = rmfield(Dnew, 'raw_tra_matrix');
        
    else        
        warning([mfilename ':DeprecatedFieldDiscrepancy'],               ...
                ['Deprecated field D.raw_tra_matrix found. \n',          ...
                 'It will be ignored, even though its contents differ ', ...
                 'from the currently saved tra matrix. \n']);
             
        % maybe leave in the raw_tra_matrix field
    end%if
end%if
  
Dnew.save;

end%save_raw_tra_to_D
